# 尝试在 addWord 的时候就把所有的可能构造出来
# 超时，因为 insert 太花时间了……
class WordDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}
        self.hasEmpty = False

    def addWord(self, word: str) -> None:
        """
        Adds a word into the data structure.
        """
        wlen = len(word)
        if wlen == 0:
            self.hasEmpty = True
            return

        self.addWordI(self.root, 0, word)

    def addWordI(self, letterMap, index, word):
        wlen = len(word)
        letter = word[index]
        if wlen - 1 == index:
            if letter not in letterMap:
                letterMap[letter] = [{}, True]
            letterMap[letter][1] = True
            if '.' not in letterMap:
                letterMap['.'] = [{}, True]
            letterMap['.'][1] = True
        else:
            if letter not in letterMap:
                letterMap[letter] = [{}, False]
            self.addWordI(letterMap[letter][0], index + 1, word)
            if '.' not in letterMap:
                letterMap['.'] = [{}, False]
            self.addWordI(letterMap['.'][0], index + 1, word)

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        """
        wlen = len(word)
        if wlen == 0:
            return self.hasEmpty

        curr = self.root
        for index, letter in enumerate(word):
            if letter in curr:
                if curr[letter][1] and index == wlen - 1:
                    return True
                curr = curr[letter][0]
            else:
                return False
        return False

# Your WordDictionary object will be instantiated and called as such:
obj = WordDictionary()
obj.addWord("at")
obj.addWord("and")
obj.addWord("an")
obj.addWord("add")
print(obj.search("a")) # false
print(obj.search(".at")) # false

obj.addWord("bat")
print(obj.search(".at"))  # true
print(obj.search("an."))  # true
print(obj.search("a.d.")) # false
print(obj.search("b."))   # false
print(obj.search("a.d"))  # true
print(obj.search("."))    # false